Branchwell

Lumen & Gesso / website · lumengesso.com / app / api / admin / orders / [id] / analyze-style / route.ts

1import { NextResponse, type NextRequest } from 'next/server';
2import { getCustomerUser } from '@/app/lib/lumen-auth';
3import { commerceDb } from '@/app/lib/commerce-db';
4import { isAdmin } from '@/app/lib/admin';
5import { describeImageStyle } from '@/app/lib/openai-vision';
6
7// POST /api/admin/orders/[id]/analyze-style
8// ----------------------------------------------------------------------
9// Sends the customer's uploaded custom_style_url to GPT-4o Vision and
10// returns a textual style description. Persists it on the order row
11// (custom_style_description + custom_style_analyzed_at) so subsequent
12// admin sessions can reuse it without re-paying the Vision call.
13//
14// Why this exists: OpenAI's /v1/images/edits endpoint only accepts one
15// reference image. Without this analysis step, custom-style commissions
16// generated via OpenAI would silently ignore the customer's uploaded
17// style and just render the pet against the catalog default. With the
18// description injected into the prompt, OpenAI now mimics the style by
19// reading it — Gemini still sees the image directly and benefits too.
20
21export const runtime = 'nodejs';
22export const dynamic = 'force-dynamic';
23
24export async function POST(
25 _req: NextRequest,
26 ctx: { params: Promise<{ id: string }> },
27) {
28 const { id } = await ctx.params;
29
30 const user = await getCustomerUser();
31 if (!user || !isAdmin(user.email)) {
32 return NextResponse.json({ error: 'forbidden' }, { status: 403 });
33 }
34
35 const admin = commerceDb();
36 const { data: order, error: orderErr } = await admin
37 .from('orders')
38 .select('id, custom_style_url')
39 .eq('id', id)
40 .single();
41 if (orderErr || !order) {
42 return NextResponse.json({ error: 'order not found' }, { status: 404 });
43 }
44 if (!order.custom_style_url) {
45 return NextResponse.json(
46 { error: 'order has no custom_style_url to analyze' },
47 { status: 400 },
48 );
49 }
50
51 let description: string;
52 try {
53 description = await describeImageStyle(order.custom_style_url);
54 } catch (e) {
55 const msg = e instanceof Error ? e.message : String(e);
56 return NextResponse.json({ error: `vision failed: ${msg}` }, { status: 500 });
57 }
58
59 const analyzedAt = new Date().toISOString();
60 const { error: updErr } = await admin
61 .from('orders')
62 .update({
63 custom_style_description: description,
64 custom_style_analyzed_at: analyzedAt,
65 })
66 .eq('id', id);
67 if (updErr) {
68 return NextResponse.json({ error: `update failed: ${updErr.message}` }, { status: 500 });
69 }
70
71 return NextResponse.json({ description, analyzedAt });
72}